#include "Serializable.h"



#include <QDir>
#include <QTextStream>



Serializable::Serializable()
{
    data = new Data;
}



Serializable::Serializable(const Serializable& other)
{
    setFilePath(other.filePath());
}



void Serializable::setFilePath(const QString& file_path)
{
    data->file_info.setFile(file_path);
}



QString Serializable::filePath() const
{
    return data->file_info.absoluteFilePath();
}



QFileInfo Serializable::fileInfo() const
{
    return data->file_info;
}



QString Serializable::error() const
{
    return data->last_error;
}


void Serializable::setDirty(const bool& dirty)
{
    data->dirty = dirty;
}


bool Serializable::isDirty() const
{
    return data->dirty;
}

bool Serializable::save()
{
    if (serializedData().isEmpty())
    {
        data->last_error = "Save Error: Written data is empty!";
        return false;
    }


    if (filePath().isEmpty())
    {
        data->last_error = "Save Error: Empty file name!";
        return false;
    }


    QFile file(filePath());
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        data->last_error = QString("%1:\n'%2'?").arg("Failed to open file").arg(filePath());
        return false;
    }


    QTextStream writer(&file);
    writer << serializedData();

    setDirty(false);

    QDir::setCurrent(data->file_info.absolutePath());
    return true;
}



bool Serializable::saveAs(const QString& file_path)
{
    setFilePath(file_path);

    return save();
}



bool Serializable::open(const QString& file_path)
{
    if (file_path.isEmpty())
    {
        data->last_error = QT_TR_NOOP("Open Error: Empty file name!");
        return false;
    }

    QFile file(file_path);
    if (!file.exists())
    {
        data->last_error = QString("%1 '%2'").arg(QT_TR_NOOP("Open Error: File does not exist!")).arg(file_path);
        return false;
    }


    if (!file.open(QIODevice::ReadOnly))
    {
        data->last_error = QString("%1 '%2'").arg(QT_TR_NOOP("Open Error: Failed to open file!")).arg(file_path);
        return false;
    }

    setSerializedData(file.readAll());

    setFilePath(file_path);
    setDirty(false);

    QDir::setCurrent(data->file_info.absolutePath());
    return true;
}



